package com.lz.autotest.project.system.service.impl;

import com.lz.autotest.common.constant.ErrMsgConstant;
import com.lz.autotest.common.constant.PermConstant;
import com.lz.autotest.project.system.domain.SysUser;
import com.lz.autotest.common.exception.ServiceException;
import com.lz.autotest.common.utils.SecurityUtils;
import com.lz.autotest.common.utils.StringUtils;
import com.lz.autotest.project.system.domain.perm.*;
import com.lz.autotest.project.system.service.ISysUserPermService;
import com.lz.autotest.project.system.mapper.SysUserPermMapper;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SysUserPermServiceImpl implements ISysUserPermService {


    @Autowired
    SysUserPermMapper userPermMapper;


    @Override
    public List<SysUserPerm> selectUserPermList(SysUserPerm sysUserPerm) {
       return userPermMapper.selectUserPermList(sysUserPerm);
    }


    @Override
    public List<AccUser> selectUserAccPermList(AccUser accUser) {
        return userPermMapper.selectUserAccPermList(accUser);
    }

    @Override
    public List<AccUser> selectDeptAccPermList(AccUser accUser) {
        return userPermMapper.selectDeptAccPermList(accUser);
    }
    @Override
    public List<GroupUser> selectUserGroupPermList(GroupUser groupUser) {
        return userPermMapper.selectUserGroupPermList(groupUser);
    }

    @Override
    public List<GroupUser> selectDeptGroupPermList(GroupUser groupUser) {
        return userPermMapper.selectDeptGroupPermList(groupUser);
    }
    @Override
    public List<CfgUser> selectUserCfgPermList(CfgUser cfgUser) {
        return userPermMapper.selectUserCfgPermList(cfgUser);
    }

    @Override
    public List<CfgUser> selectDeptCfgPermList(CfgUser cfgUser) {
        return userPermMapper.selectDeptCfgPermList(cfgUser);
    }


    @Override
    public List<IrcUser> selectUserIrcPermList(IrcUser ircUser) {
        return userPermMapper.selectUserIrcPermList(ircUser);
    }

    @Override
    public List<IrcUser> selectDeptIrcPermList(IrcUser ircUser) {
        return userPermMapper.selectDeptIrcPermList(ircUser);
    }

    @Override
    public List<DivUser> selectUserDivPermList(DivUser divUser) {
        return userPermMapper.selectUserDivPermList(divUser);
    }
    @Override
    public List<DivUser> selectDeptDivPermList(DivUser divUser) {
        return userPermMapper.selectDeptDivPermList(divUser);
    }
    @Override
    public List<VlsUser> selectUserVolPermList(VlsUser vlsUser) {
        return userPermMapper.selectUserVolPermList(vlsUser);
    }
    @Override
    public List<VlsUser> selectDeptVolPermList(VlsUser vlsUser) {
        return userPermMapper.selectDeptVolPermList(vlsUser);
    }

    @Override
    public List<SysUserPerm> selectAllUserPermList() {
        return null;
    }

    @Override
    public SysUserPerm selectUserPermById(Long userId) {
        return userPermMapper.selectUserPermListByUserId(userId);
    }

    @Override
    public List<Map> selectAllAccount() {
        return userPermMapper.selectAllAccount();
    }

    @Override
    public List<Map> selectAllGroup() {
        return userPermMapper.selectAllGroup();
    }

    @Override
    public List<Map> selectAllCfg() {
        return userPermMapper.selectAllCfg();
    }

    @Override
    public int deleteUserPermById(Long userId) {
        return 0;
    }

    @Override
    public int deleteUserPermByIdS(Long[] userIds) {
        return userPermMapper.clearUserPerm(userIds);
    }
    @Override
    public int clearUserPermDetail(Long[] userIds) {
        userPermMapper.deleteAccUser(userIds);
        userPermMapper.deleteCfgUser(userIds);
        userPermMapper.deleteIrcUser(userIds);
        userPermMapper.deleteDivUser(userIds);
        userPermMapper.deleteVlsUser(userIds);
        return userPermMapper.clearUserPermDetail(userIds);
    }


    @Override
    public int insertUserPerm(SysUserPerm userPerm) {
        return userPermMapper.insertUserPerm(userPerm);
    }

    @Override
    public int updateUserPerm(SysUserPerm userPerm) {
        SysUserPerm oriSysUserPerm=userPermMapper.selectUserPermListByUserId(userPerm.getUserId());
        String[] nAccId=userPerm.getAccId().split(",");
        String[] nCfgId=userPerm.getCfgId().split(",");
        String[] nIrcCode=userPerm.getIrcCode().split(",");
        String[] nDivCode=userPerm.getDivCode().split(",");
        String[] nVlsCode=userPerm.getVlsCode().split(",");
        String[] accIds=oriSysUserPerm.getAccId()==null?new String[1]:oriSysUserPerm.getAccId().split(",");
        List<AccUser> accUserDelList=new ArrayList<>();
        if(!("").equals(oriSysUserPerm.getAccId())&& StringUtils.isNotNull(oriSysUserPerm.getAccId())&&accIds.length>0) {
            //找到账户修改后删减的账户权限
            for (String accId:accIds) {
                if(!Arrays.asList(nAccId).contains((accId))){
                    AccUser au=new AccUser();
                    au.setUserId(userPerm.getUserId());
                    au.setAccId(accId);
                    accUserDelList.add(au);
                }
            }
            if(accUserDelList.size()>0){
                userPermMapper.batchDeleteAccountUser(userPerm.getUserId(),accUserDelList);
            }

        }
        List<AccUser> accUserAddList=new ArrayList<>();
        //找到修改后增加的账户权限，赋为2:写权限
        if(!("").equals(userPerm.getAccId())&&StringUtils.isNotNull(userPerm.getAccId())&&nAccId.length>0) {
            //找到账户修改后增加的账户权限
            for (String accId:nAccId) {
                if(!Arrays.asList(accIds).contains((accId))){
                    AccUser au=new AccUser();
                    au.setUserId(userPerm.getUserId());
                    au.setAccId(accId);
                    au.setAccRight("2");
                    accUserAddList.add(au);
                }
            }
            if(accUserAddList.size()>0){
                userPermMapper.batchInsertAccountUser(accUserAddList);
            }
        }
        String[] cfgIds=oriSysUserPerm.getCfgId()==null?new String[1]:oriSysUserPerm.getCfgId().split(",");
        if(!("").equals(oriSysUserPerm.getCfgId())&&StringUtils.isNotNull(oriSysUserPerm.getCfgId())&&cfgIds.length>0) {
            List<CfgUser> cfgUserDelList=new ArrayList<>();
            //找到定价配置修改后删减的配置权限
            for (String cfgId:cfgIds) {
                if(!Arrays.asList(nCfgId).contains((cfgId))){
                    CfgUser au=new CfgUser();
                    au.setUserId(userPerm.getUserId());
                    au.setCfgId(cfgId);
                    cfgUserDelList.add(au);
                }
            }
            if(cfgUserDelList.size()>0){
                userPermMapper.batchDeleteCfgUser(userPerm.getUserId(),cfgUserDelList);
            }
        }

        //找到修改后增加的配置权限,，赋为2:写权限
        if(!("").equals(userPerm.getCfgId())&&StringUtils.isNotNull(userPerm.getCfgId())&&nCfgId.length>0) {
            List<CfgUser> cfgUserAddList=new ArrayList<>();
            //找到账户修改后删减的账户权限
            for (String cfgId:nCfgId) {
                if(!Arrays.asList(cfgIds).contains((cfgId))){
                    CfgUser au=new CfgUser();
                    au.setUserId(userPerm.getUserId());
                    au.setCfgId(cfgId);
                    au.setCfgRight("2");
                    cfgUserAddList.add(au);
                }
            }
            if(cfgUserAddList.size()>0){
                userPermMapper.batchInsertCfgUser(cfgUserAddList);
            }
        }

        String[] ircCodes = oriSysUserPerm.getIrcCode() == null ? new String[1] : oriSysUserPerm.getIrcCode().split(",");
        if(!("").equals(oriSysUserPerm.getIrcCode()) && StringUtils.isNotNull(oriSysUserPerm.getIrcCode()) && ircCodes.length>0 && ircCodes[0] != "" ) {
            List<IrcUser> ircUserDelList=new ArrayList<>();
            //找到利率修改后删减的配置权限
            for (String ircCode:ircCodes) {
                if(!Arrays.asList(nIrcCode).contains((ircCode))){
                    IrcUser au = new IrcUser();
                    au.setUserId(userPerm.getUserId());
                    au.setIrcCode(ircCode);
                    ircUserDelList.add(au);
                }
            }
            if(ircUserDelList.size()>0){
                userPermMapper.batchDeleteIrcUser(userPerm.getUserId(),ircUserDelList);
            }
        }
        //找到修改后增加的配置权限,，赋为2:写权限
        if(!("").equals(userPerm.getIrcCode()) && StringUtils.isNotNull(userPerm.getIrcCode()) && nIrcCode.length>0 && nIrcCode[0] != "") {
            List<IrcUser> ircUserAddList=new ArrayList<>();
            //找到利率修改后删减的账户权限
            for (String ircCode:nIrcCode) {
                if(!Arrays.asList(ircCodes).contains((ircCode))){
                    IrcUser au = new IrcUser();
                    au.setUserId(userPerm.getUserId());
                    au.setIrcCode(ircCode);
                    au.setIrcRight("2");
                    ircUserAddList.add(au);
                }
            }
            if(ircUserAddList.size()>0){
                userPermMapper.batchInsertIrcUser(ircUserAddList);
            }
        }

        String[] divCodes = oriSysUserPerm.getDivCode() == null ? new String[1] : oriSysUserPerm.getDivCode().split(",");
        if(!("").equals(oriSysUserPerm.getDivCode()) && StringUtils.isNotNull(oriSysUserPerm.getDivCode()) && divCodes.length>0 && divCodes[0] != "") {
            List<DivUser> divUserDelList=new ArrayList<>();
            //找到定价配置修改后删减的配置权限
            for (String divCode:divCodes) {
                if(!Arrays.asList(nDivCode).contains((divCode))){
                    DivUser au = new DivUser();
                    au.setUserId(userPerm.getUserId());
                    au.setDivCode(divCode);
                    divUserDelList.add(au);
                }
            }
            if(divUserDelList.size()>0){
                userPermMapper.batchDeleteDivUser(userPerm.getUserId(),divUserDelList);
            }
        }
        //找到修改后增加的配置权限,，赋为2:写权限
        if(!("").equals(userPerm.getVlsCode()) && StringUtils.isNotNull(userPerm.getVlsCode()) && nDivCode.length>0 && nDivCode[0] != "") {
            List<DivUser> divUserAddList=new ArrayList<>();
            //找到账户修改后删减的账户权限
            for (String divCode:nDivCode) {
                if(!Arrays.asList(divCodes).contains((divCode))){
                    DivUser au = new DivUser();
                    au.setUserId(userPerm.getUserId());
                    au.setDivCode(divCode);
                    au.setDivRight("2");
                    divUserAddList.add(au);
                }
            }
            if(divUserAddList.size()>0){
                userPermMapper.batchInsertDivUser(divUserAddList);
            }
        }

        String[] vlsCodes = oriSysUserPerm.getVlsCode() == null ? new String[1] : oriSysUserPerm.getVlsCode().split(",");
        if(!("").equals(oriSysUserPerm.getVlsCode()) && StringUtils.isNotNull(oriSysUserPerm.getVlsCode()) && vlsCodes.length>0 && vlsCodes[0] != "") {
            List<VlsUser> vlsUserDelList=new ArrayList<>();
            //找到定价配置修改后删减的配置权限
            for (String vlsCode:vlsCodes) {
                if(!Arrays.asList(nVlsCode).contains((vlsCode))){
                    VlsUser au = new VlsUser();
                    au.setUserId(userPerm.getUserId());
                    au.setVlsCode(vlsCode);
                    vlsUserDelList.add(au);
                }
            }
            if(vlsUserDelList.size()>0){
                userPermMapper.batchDeleteVlsUser(userPerm.getUserId(),vlsUserDelList);
            }
        }
        //找到修改后增加的配置权限,，赋为2:写权限
        if(!("").equals(userPerm.getVlsCode()) && StringUtils.isNotNull(userPerm.getVlsCode()) && nVlsCode.length>0 && nVlsCode[0] != "") {
            List<VlsUser> vlsUserAddList=new ArrayList<>();
            //找到账户修改后删减的账户权限
            for (String vlsCode:nVlsCode) {
                if(!Arrays.asList(vlsCodes).contains((vlsCode))){
                    VlsUser au = new VlsUser();
                    au.setUserId(userPerm.getUserId());
                    au.setVlsCode(vlsCode);
                    au.setVlsRight("2");
                    vlsUserAddList.add(au);
                }
            }
            if(vlsUserAddList.size()>0){
                userPermMapper.batchInsertVlsUser(vlsUserAddList);
            }
        }

        //修改权限表本身
        return userPermMapper.updateUserPerm(userPerm);
    }


    @Override
    public int edtUserAccPerm(AccUser accUser) {
        return userPermMapper.edtUserAccPerm(accUser);
    }
    @Override
    public int edtUserGroupPerm(GroupUser groupUser) {
        if(groupUser.getGroupRight().equals("0")){
            //不分读写 只有无权限时进行修改 sql中处理了非全部的判断
            return userPermMapper.edtUserGroupPerm(groupUser);
        }
        return 1;
    }

    @Override
    public int edtUserCfgPerm(CfgUser accUser) {
        return userPermMapper.edtUserCfgPerm(accUser);
    }

    @Override
    public int edtUserIrcPerm(IrcUser ircUser) {
        return userPermMapper.edtUserIrcPerm(ircUser);
    }

    @Override
    public int edtUserDivPerm(DivUser divUser) {
        return userPermMapper.edtUserDivPerm(divUser);
    }

    @Override
    public int edtUserVlsPerm(VlsUser vlsUser) {
        return userPermMapper.edtUserVlsPerm(vlsUser);
    }
    @Override
    public String getUserPermFlag(String authType,String userId) {
        return userPermMapper.getUserPermFlag(authType,userId);
    }

    /**
     *必须包含uRight和dRight两个结果的List<Map> 在该方法处根据用户进行数据筛选
     * @param list
     * @param authType
     * @return
     */
    public  List<Map> filterAuth(List<Map> list,String authType){
        PermConstant.PERM_TYPE permObject = PermConstant.PERM_TYPE.getPermType(authType);
        if(permObject==null){
            throw new ServiceException(ErrMsgConstant.AUTH_ERR);
        }
        //查询当前用户权限
        if("0".equals(userPermMapper.getUserPermFlag(permObject.getFlagItem(), SecurityUtils.getUserId().toString()))){
            //不分配部门权限，则直接使用自己的权限
            list.stream().forEach(m -> m.put(permObject.getRightItem(), MapUtils.getString(m,"uRight")));
        }else{
            //分配部门权限，则取部门的权限
            list.stream().forEach(m -> m.put(permObject.getRightItem(),MapUtils.getString(m,"dRight")));
        }
        //对无权限的进行过滤
        Object o=list.stream().filter(m ->MapUtils.getString(m,permObject.getRightItem())!=null&&MapUtils.getIntValue(m,permObject.getRightItem()) > 0).collect(Collectors.toList());
        return (List<Map>) o;
    }

    /**
     * 根据权限类型查询权限标志
     * @param authType
     * @return
     */
    public  String getPermFlag(String authType){
        PermConstant.PERM_TYPE permObject = PermConstant.PERM_TYPE.getPermType(authType);
        if(permObject==null){
            throw new ServiceException(ErrMsgConstant.AUTH_ERR);
        }
        return userPermMapper.getUserPermFlag(permObject.getFlagItem(), SecurityUtils.getUserId().toString());
    }
    @Override
    public List<SysUser> selectCfgAllocateUserList(Map map) {
        return userPermMapper.selectCfgAllocateUser(map);
    }
}
